package com.sdcqjy.property.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.sdcqjy.mylibrary.Logger;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseService;
import com.sdcqjy.property.base.SimpleBaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * webView展示页
 */
public class WebViewActivity extends SimpleBaseActivity {
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.textTitle)
    TextView textTitle;
    private String url;
    private boolean isHtml;
    private String title;

    public static final String FullAll = "function fullscreen() {" +
            "  var docElm = document.documentElement;" +
            "  if (docElm.requestFullscreen) {" +
            "    docElm.requestFullscreen();" +
            "  } else if (docElm.mozRequestFullScreen) {" +
            "    docElm.mozRequestFullScreen();" +
            "  } else if (docElm.webkitRequestFullScreen) {" +
            "    docElm.webkitRequestFullScreen();" +
            "  } else if (docElm.msRequestFullscreen) {" +
            "    docElm.msRequestFullscreen();}}";
    public static final String JsImageZoom =
            "function ResizeImages() {"
                    + "maxH=document.body.scrollHeight;"
                    + "total=0;"
                    + "h=document.body.clientHeight;"
                    + "w=document.body.clientWidth;"
                    + " var myimg,oldwidth;"
                    + "var maxwidth=w-20 "
                    + ";for(i=0;i <document.images.length;i++){"
                    + "myimg = document.images[i];"
                    + "if(myimg.width > maxwidth){"
                    + "total+=myimg.height;"
                    + "oldwidth = myimg.width;"
                    + "myimg.width = maxwidth;"
                    + "total-=myimg.height;}" + "}"
                    + "myObj.setWebH(maxH-total);}";

    private void zoom() {
        if (android.os.Build.VERSION.SDK_INT >= 19) {
            webView.loadUrl("javascript:(function(){"
                    + "var objs = document.getElementsByTagName('img'); "
                    + "for(var i=0;i<objs.length;i++) {"
                    + // //webview图片自适应，android4.4之前都有用，4.4之后google优化后，无法支持，需要自己手动缩放
                    " objs[i].style.width = '100%';objs[i].style.height = 'auto';"
                    + "}"
                    + "})()"
            );
        } else {
            webView.loadUrl("javascript:var imgs = document.getElementsByTagName('img');for(var i = 0; i<imgs.length; i++){imgs[i].style.width = '100%';imgs[i].style.height = 'auto';}");
        }
    }

    public static void open(Context context, String title, String content) {
        open(context, title, content, false);
    }

    public static void open(Context context, String title, String content, boolean isHtml) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", content);
        intent.putExtra("isHtml", isHtml);
        context.startActivity(intent);
    }

    @SuppressLint("JavascriptInterface")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        title = intent.getStringExtra("title");
        isHtml = intent.getBooleanExtra("isHtml", false);

        WebSettings settings = webView.getSettings();

        //缩放开关，设置此属性，仅支持双击缩放，不支持触摸缩放
        settings.setSupportZoom(true);
        //设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
        settings.setBuiltInZoomControls(true);
        //隐藏缩放工具
        settings.setDisplayZoomControls(false);

        webView.setBackgroundColor(0xffFFffFF);

        settings.setJavaScriptEnabled(true);
        //webView.addJavascriptInterface(new AppOpert(), "androidObj");
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.out(url);
                if (url.equals("about:blank") || url.startsWith("mailto:")) {
                } else if (url.startsWith("tel:")) {//电话
                    OtherUtils.callTelOfUri(getActivity(), url);
                } else {
                    webView.loadUrl(url);
                }
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                //执行图片缩放
//                if (android.os.Build.VERSION.SDK_INT >= 21) {
//                    zoom();
//                } else {
                webView.loadUrl("javascript:" + FullAll);
                webView.loadUrl("javascript:fullscreen()");
//                }
            }
        });
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url1);
            Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent1);
            onBackPressed();
        });
        //“file:///android_asset/sample.html”
        if (isHtml)
            webView.loadDataWithBaseURL(BaseService.ImgURL, url, "text/html", "utf-8", null);
        else webView.loadUrl(url);
        if (!TextUtils.isEmpty(title)) textTitle.setText(title);
//        webView.findAllAsync(content);
//        webView.clearMatches();
    }

    @OnClick({R.id.imgBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgBack:
                if (webView.canGoBack()) {
                    webView.goBack();// 返回前一个页面
                } else onBackPressed();
                break;
        }
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();// 返回前一个页面
            } else onBackPressed();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 继承WebChromeClient类
     * 对js弹出框时间进行处理
     */
    final class MyWebChromeClient extends WebChromeClient {

        /**
         * 处理alert弹出框
         */
        @Override
        public boolean onJsAlert(WebView view, String url,
                                 String message, JsResult result) {
            new AlertDialog.Builder(WebViewActivity.this).
                    setTitle("Alert").setMessage(message).setPositiveButton("OK",
                    (arg0, arg1) -> {
                        //TODO
                    }).create().show();
            result.confirm();
            return true;
        }

        /**
         * 处理confirm弹出框
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   JsResult result) {
            result.confirm();
            return super.onJsConfirm(view, url, message, result);
        }

        /**
         * 处理prompt弹出框
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            result.confirm();
            return super.onJsPrompt(view, url, message, message, result);
        }
    }
}
